define([
  'controllers/common/showModal',
  'text!plugins/FastPath/templates/map/controls/generalInfo_ErrorItem.html',
  'text!plugins/FastPath/templates/map/controls/generalInfo.html',
  'text!plugins/FastPath/templates/map/controls/generalInfo_SubcorridorItem.html',
  'text!plugins/FastPath/templates/map/controls/generalInfo_CorridorItem.html',
  'text!plugins/FastPath/templates/map/controls/generalInfo_CorridorFull.html',
  'text!plugins/FastPath/templates/map/controls/generalInfo_SubcorridorItem_Link.html',
], function (ModalController, HTMLTemplate_ErrorItem, HTMLTemplate, HTMLSubcorridorItem, HTMLCorridorItem, HTMLCorridorFull, HTMLSubcorridorLink) {

  var view = Backbone.View.extend({
      el: $("#main"),
      uploader: undefined,
      currentSubcorridor: undefined,
      currentSortLink: undefined,
      deletedCorridors: [],
      deletedSubcorridors: [],
      layersDictionary:undefined,
      render: function () {

        this.deletedCorridors = [];
        this.deletedSubcorridors = [];

        var template = Handlebars.compile(HTMLTemplate);
        var html = template();
        this.$el.html(html);

        //update height
        var h = $("#main").height();
        $("#projectmap .generalinfo").height(h - 25);
        $("#projectmap .generalinfo .corridor-container").height(h - 25 -66);
        this.addHandlers();

        this.layersDictionary = {};


      
          
          
          //addlayerview
      },
     expandControl: function () {
        var $this = $(".leaflet-infobar .generalinfo button[data-rel='toggle']");
        $this.attr("data-expanded", "1");
        $this.find("i").attr("class", "icon-angle-up");
        $this.closest(".leaflet-control").removeClass("contracted");
    },
     contractControl: function () {
        var $this = $(".leaflet-infobar .generalinfo button[data-rel='toggle']");
        $this.attr("data-expanded", "0");
        $this.find("i").attr("class", "icon-angle-down");
        $this.closest(".leaflet-control").addClass("contracted");
     },
     removeView:function(){
         $.contextMenu('destroy', '.giContextMenu');
         this.layersDictionary = null;
     },
    addHandlers: function () {
        var _this = this;

        // save
        $(".leaflet-infobar .generalinfo button[data-rel='save']").click(function () {
            $("#projectMapSidebar").trigger("saveProject");
        });

        $(".leaflet-infobar .generalinfo button[data-rel='refresh']").click(function () {
            $("#projectMapSidebar").trigger("refreshProject");
        });

        


        //back to projects
        $(".leaflet-infobar .generalinfo button[data-rel='backtoprojects']").click(function () {

            $("#projectmap").trigger("isOkToBack", [function (isOK) {

                if (isOK) {
                    $("#projectmap").trigger("setMode", ["free"]);
                    $("#projectmap").trigger("removeControlsForBuild");
                    $("#projectMapSidebar").trigger("showFPCases");
                }
            }]);
        });

        //evaluate
        
        $(".leaflet-infobar .generalinfo button[data-rel='evaluate_fpCase']").click(function () {

            if ($(".leaflet-infobar .generalinfo button[data-rel='save']").hasClass("btn-red")) {
                showMessage(translate("save_changes_then_evaluate"));
            }
            else {
                $("#projectMapSidebar").trigger("evaluateFPCase");
            }

        });

        // Assign demand costs
        $(".leaflet-infobar .generalinfo button[data-rel='assign_demand_costs']").click(function () {

            $("#projectMapSidebar").trigger("assignDemandPerSubcorridor");

        });


        // error list
        $(".leaflet-infobar .errorList ul").on("click" , "li a", function () {
            var lat = $(this).attr("data-lat");
            var lng = $(this).attr("data-lng");
            $("#projectmap").trigger("moveMapTo", [lat, lng]);
            $("#projectmap").trigger("showAlertMessage", [lat, lng, $(this).closest("li").find("span").html()]);
            return false;
        });

        // click on left list to show popup
        $(".leaflet-infobar .generalinfo .corridor-container").on("click", ".subcorridorItemContainer li table td", function () {
            var entityId = $(this).attr("data-value");
            var geometryType = ($(this).attr("data-type") == "node" ? 1 : 2);
            $("#projectmap").trigger("showLayerPopup", [entityId, geometryType]);
        });


        // click on subcorridor to expand / contract 
        $(".leaflet-infobar .generalinfo .corridor-container").on("click", ".subcorridorItemContainer li a.subcorridor, .subcorridorItemContainer li i.expandor", function () {
            if ($(this).closest("li").hasClass("contracted")) {
                _this.sortSubcorridor($(this).closest("li").attr("data-id"));
            }
            $(this).closest("li").toggleClass("contracted")
        });



        //over link/node to show on map
        $(".leaflet-infobar .generalinfo .corridor-container").on("mouseover", ".subcorridorItemContainer li table tr", function () {
            if (!$(this).closest("li").hasClass("selecting")) {
                var leafletid = $(this).attr("data-leaflet");
                $("#projectmap").trigger("showLinksOrNode", [leafletid]);
            }
        });
        $(".leaflet-infobar .generalinfo .corridor-container").on("mouseout", ".subcorridorItemContainer li table tr", function () {

            if (!$(this).closest("li").hasClass("selecting")) {
                $("#projectmap").trigger("clearAuxLayer");
            }
        });

        // over subcorridor to show on map
        $(".leaflet-infobar .generalinfo .corridor-container").on("mouseover", ".subcorridorItemContainer a.subcorridor", function () {
            if (!$(this).closest("li").hasClass("selecting")) {
                var arr = _this.getLayersFromLi($(this).closest("li"));
                if (arr && arr.length > 0) {
                    $("#projectmap").trigger("drawAuxLayers", [arr]);
                }
            }

        });
        $(".leaflet-infobar .generalinfo .corridor-container").on("mouseout", ".subcorridorItemContainer a.subcorridor", function () {
            if (!$(this).closest("li").hasClass("selecting")) {
                $("#projectmap").trigger("clearAuxLayer");
            }
        });




        // SUBCORRIDORS
        //add subcorridor
        $(".leaflet-infobar .generalinfo .corridor-container").on("click","button[data-action='add_subcorridor']",function () {
            var newId = $.uuid();
            var addTo = $(this).closest(".corridorList").attr("data-id");
            _this.addSubcorridor({
                tempId: newId,
                entityId: -1,
                name: "("+translate("new_subcorridor")+")"
            },addTo);
            _this.editSubCorridor(newId);
        });



        $(".leaflet-infobar .generalinfo .corridor-container").on("click", "button.giContextMenu", function () {
            $(this).contextMenu();
        });
        
       

        $.contextMenu({
            selector: '.giContextMenu',
            callback: function (key, options) {

                var $li = options.$trigger.closest("li");

                switch (key) {
                    case "_edit":
                        var id = $li.attr("data-id");
                        _this.editSubCorridor(id);
                        break;

                    case "_copy":
                        var $newLi = $li.clone().appendTo($li.closest("ul"));
                        var name = $newLi.find("a.subcorridor").text();
                        $newLi.find("a.subcorridor").text(translate("copy_of") + " " + name);
                        var newId = $.uuid();
                        $newLi.attr("data-id", newId);
                        $newLi.attr("data-entity-id", -1);
                        $newLi.addClass("modified");

                        //duplicate subcorridor data links
                        var arr = _this.layersDictionary[$li.attr("data-id")];
                        if (arr) {
                            arr = arr.slice(0); //clone
                            _this.layersDictionary[newId] = arr;
                        }
                        _this.addSubcorridorSortable();
                        _this.editSubCorridor(newId);
                        break;

                    case "_delete":
                        if ($(".leaflet-infobar .generalinfo .corridorList .subcorridorItemContainer li").length == 1) {
                            showMessage(translate("cantnot_remove_last_subcorridor"));
                        }
                        else {

                            (new ModalController()).show({
                                title: translate("warning"),
                                text: translate("sure_remove_subcorridor"),
                                buttons: [
                                    { "title": translate("yes"), "css": "primary", "code": "yes" },
                                    { "title": translate("no"), "code": "no" },
                                ],
                                callback: function (code) {
                                    if (code == "yes") {

                                        if ($li.attr("data-entity-id")) {
                                            _this.deletedSubcorridors.push($li.attr("data-entity-id"));
                                        }
                                        $li.remove();
                                        $("#projectmap").trigger("changeModeOn");
                                        $("#projectmap").trigger("validateIntegrity");
                                    }
                                }
                            });
                        }
                        break;

                    case "_info":
                        var entityId = $li.attr("data-entity-id");
                        if (entityId != "-1") {
                            $("#projectMapSidebar").trigger("showSubcorridorForm", [entityId]);
                        }
                        else {
                            showMessage(translate("save_changes_then_put_info"));
                        }
                        break;
                }

                
            },
            items: {
                "_edit": { type: "icon_text", name: translate("edit_subcorridor"), iconClass: "icon-edit" },
                "_copy": { type: "icon_text", name: translate("copy_subcorridor"), iconClass: "icon-copy" },
                "_delete": { type: "icon_text", name: translate("remove_subcorridor"), iconClass: "icon-trash" },
                "_info": { type: "icon_text", name: translate("add_subcorridor_data"), iconClass: "icon-info-sign" }
            }
        });


        // define subcorridor
        $(".leaflet-infobar .generalinfo .corridor-container").on("click", "button[data-action='define_subcorridor']", function () {

            if ($(this).closest("li").hasClass("contracted")) {
                _this.sortSubcorridor($(this).closest("li").attr("data-id"));
                $(this).closest("li").removeClass("contracted");
            }
            var id = $(this).closest("li").attr("data-id");
            $(".leaflet-infobar .generalinfo .subcorridorItemContainer li[data-id!='"+id+"']").removeClass("selecting");

            // show if it is hidden
            if ($(this).closest("li").hasClass("subcorridor_hidden")) {
                $(this).closest("li").find("button[data-action='hide_subcorridor']").click();
            }

            $(this).closest("li").toggleClass("selecting");

            if ($(this).closest("li").hasClass("selecting")) {
                _this.currentSubcorridor = id;
                $("#projectmap").trigger("setMode", ["selectLinks"]);
                var arr = _this.getLayersFromLi( $(this).closest("li"));
                if (arr){
                    $("#projectmap").trigger("drawAuxLayers", [ arr ]);
                }
            }
            else {
                $("#projectmap").trigger("setMode", ["free"]);
            }
        });



        // show/hide subcorridor
        $(".leaflet-infobar .generalinfo .corridor-container").on("click", "button[data-action='hide_subcorridor']", function () {
            
            var arr = _this.getLayersFromLi($(this).closest("li"));
            if (arr && arr.length > 0) {
                if ($(this).closest("li").hasClass("subcorridor_hidden")) {
                    $(this).find("i").attr("class", "icon-eye-open");
                    $(this).closest("li").removeClass("subcorridor_hidden");
                    $("#projectmap").trigger("showLayers", [arr]);
                } else {
                    $(this).find("i").attr("class", "icon-eye-close");
                    $(this).closest("li").addClass("subcorridor_hidden");
                    $("#projectmap").trigger("hideLayers", [arr]);
                }
            }
            
        });




        


        // ENTER on input textbox
        $(".leaflet-infobar .generalinfo .corridor-container ").on("keypress", ".corridorList ul li input", function (e) {
            if (e.which == 13) {
                $(this).closest(".editor").find("button").first().trigger("click");
            }
        });

        // OK on edit subcorridor
        $(".leaflet-infobar .generalinfo .corridor-container ").on("click", ".corridorList ul li .editor button", function () {
            if ($(this).attr("data-action") == "ok") {
                var text = $(this).closest(".editor").find("input").val()
                $(this).closest("li").find("a").html(text);
                $(this).closest("li").addClass("modified");
                $("#projectmap").trigger("changeModeOn");
            }
            _this.clearEditSubcorridor();
        });



        // CORRIDORS
        //add corridor
        $(".leaflet-infobar .generalinfo .corridor-container").on("click", "button[data-action='add_corridor']", function () {
            var newId = $.uuid();
            _this.addCorridor({
                tempId: newId,
                name: "(" + translate("new_corridor") + ")",
                entityId: -1
            });
            _this.editCorridor(newId);
        });

        // edit corridor
        $(".leaflet-infobar .generalinfo .corridor-container").on("click", "button[data-action='edit_corridor']", function () {
            var id = $(this).closest(".corridorList").attr("data-id");
            _this.editCorridor(id);
        });

        // delete corridor
        $(".leaflet-infobar .generalinfo .corridor-container").on("click", "button[data-action='remove_corridor']", function () {
            var thisId = $(this).closest(".corridorList").attr("data-id");

            if ($(".leaflet-infobar .generalinfo .corridorList").length == 1) {
                showMessage(translate("cantnot_remove_last_corridor"));
            }
            else if ($(".leaflet-infobar .generalinfo .corridorList[data-id!='" + thisId + "'] .subcorridorItemContainer li").length == 0) {
                showMessage(translate("cantnot_remove_last_subcorridor"));
            }
            else {

                var $corridorList = $(this).closest(".corridorList");
                (new ModalController()).show({
                    title: translate("warning"),
                    text: translate("sure_remove_corridor"),
                    buttons: [
                        { "title": translate("yes"), "css": "primary", "code": "yes" },
                        { "title": translate("no"), "code": "no" },
                    ],
                    callback: function (code) {
                        if (code == "yes") {

                            if ($corridorList.attr("data-entity-id")) {
                                _this.deletedCorridors.push($corridorList.attr("data-entity-id"));
                            }

                            $corridorList.remove();
                            $("#projectmap").trigger("changeModeOn");
                            $("#projectmap").trigger("validateIntegrity");
                        }
                    }
                });

                
            }

        });
       

        // ENTER on input textbox
        $(".leaflet-infobar .generalinfo .corridor-container").on("keypress", ".corridorList .corridorEditor input", function (e) {
            if (e.which == 13) {
                $(this).closest(".editor").find("button").first().trigger("click");
            }
        });

        // OK in edit corridor
        $(".leaflet-infobar .generalinfo .corridor-container").on("click", ".corridorList .corridorEditor button", function (e) {
            if ($(this).attr("data-action") == "ok") {
                var text = $(this).closest(".editor").find("input").val()
                $(this).closest(".corridorList").find("span.corridor-title").html(text);
                $(this).closest(".corridorList").addClass("modified");
                $("#projectmap").trigger("changeModeOn");
            }
            _this.clearEditCorridor();
        });
        


    },

    editSubCorridor: function (id) {
        this.clearEditSubcorridor();
        this.clearEditCorridor();

        this.$el.find(".corridorList ul li[data-id='" + id + "'] .subcorridor-wrapper").hide()
        
        // enter in edit mode
        var $editor = this.$el.find(".corridorList ul li[data-id='" + id + "'] .editor");
        $editor.removeClass("nodisplay");
        $editor.find("input").val($editor.closest("li").find("a").text());

        setTimeout(function () {
            $editor.find("input").select();
        }, 50);
       
        $("#projectmap").trigger("resetMode");

    },
    clearEditSubcorridor: function () {
        $("#projectmap").trigger("setMode", ["free"]);
        this.$el.find(".corridorList ul li .editor").addClass("nodisplay");
        this.$el.find(".corridorList .subcorridorItemContainer .subcorridor-wrapper").show();
        this.currentSubcorridor = undefined;
    },
    addSubcorridor: function (data,addTo) {
        this.clearEditSubcorridor();

        var template = Handlebars.compile(HTMLSubcorridorItem);
        var html = template(data);
        this.$el.find(".corridorList[data-id='" + addTo + "'] ul").append(html);
        this.addSubcorridorSortable();
        this.sortSubcorridor(data.tempId);
    },
    addCorridor: function (data) {

        var template = Handlebars.compile(HTMLCorridorItem);
        var html = template(data);
        this.$el.find(".corridor-container .errorList").before(html);
        this.addSubcorridorSortable();
    },
    editCorridor: function (id) {
        this.clearEditSubcorridor();
        this.clearEditCorridor();

        this.$el.find(".corridorList[data-id='" + id + "'] .corridor-wrapper").hide();

        // enter in edit mode
        var $editor = this.$el.find(".corridorList[data-id='" + id + "'] .corridorEditor");
        $editor.removeClass("nodisplay");
        $editor.find("input").val($editor.closest(".corridorList").find("span.corridor-title").text());
        setTimeout(function () {
            $editor.find("input").select();
        }, 50);

        $("#projectmap").trigger("resetMode");
    },
    clearEditCorridor: function () {
        this.$el.find(".corridorList .corridor-wrapper").show();
        this.$el.find(".corridorList .editor").addClass("nodisplay");
    },
    addSubcorridorSortable: function(){
        //
        var _this = this;
        $(".leaflet-infobar .generalinfo .corridor-container .subcorridorItemContainer").sortable({
            connectWith: ".subcorridorItemContainer",
            handle: "i.sorter",
            axis: "y",
            placeholder: "subcorridorplaceholder",
            start: function (event, ui) {
                $(ui.helper).addClass("modified");
                $("#projectmap").trigger("resetMode");
                $("#projectmap").trigger("changeModeOn");
            }
        }).disableSelection();



        $(".leaflet-infobar .generalinfo .corridor-container .subcorridorItemContainer table tbody").sortable({
            axis: "y",
            start: function (event, ui) {
                _this.currentSortLink = $(this).find("tr").first().attr("data-leaflet");
            },
            stop: function (event, ui) {
                var itemTbody = this;

                setTimeout(function () {
                    if (_this.sortSubcorridor($(itemTbody).closest("li").attr("data-id"))){
                        var arr = _this.getLayersFromLi($(itemTbody).closest("li"));
                        if (arr) {
                            var firstId = parseInt($(itemTbody).find("tr").first().attr("data-leaflet"));
                            if (arr.indexOf(firstId) >= 0) {
                                arr.splice(arr.indexOf(firstId), 1);
                                arr.unshift(firstId);
                                $(itemTbody).closest("li").addClass("modified");
                            }
                        }
                    }

                }, 100);

                $("#projectmap").trigger("resetMode");
                $("#projectmap").trigger("changeModeOn");
    
            }
        }).disableSelection();


    },
    updateIntegrityStatus: function (isError, itemCount) {
        $(".corridor-container .integrityErrorOn").hide();
        $(".corridor-container .integrityErrorOff").hide();

        if (itemCount>0) {
            if (isError) {
                $(".corridor-container .integrityErrorOn").show();
            }
            else {
                $(".corridor-container .integrityErrorOff").show();
            }
        }


    },
    // show list of errors
    showIntegrityErrors: function (errorList) {
        var template = Handlebars.compile(HTMLTemplate_ErrorItem);
        var html = template({ errorData: errorList });
        this.$el.find(".errorList ul").html(html);
        this.$el.find(".errorList").show();

        //this.expandControl();
    },
    clearIntegrityErrors: function () {
        this.$el.find(".errorList").hide();
        this.$el.find(".errorList ul").html("");
    },
     // return the subcorridor temp id where layerid is in
    getSubcorridorIdFromLayerId:function(layerId){

        var res = [];
        var _this=this;
        this.$el.find(".corridorList ul li").each(function (nn, item) {

            var arr =  _this.getLayersFromLi($(this));
            if (arr) {
                var index = arr.indexOf(layerId);
                if (index > -1) {
                    res.push($(this).attr("data-id"));
                }
            }
        });

        return res;

    },
    //add selected layer to current editable subcorridor
    addSelectedLayer: function (id, tempId, updateCorridor, linkData) {


        var key=this.currentSubcorridor;
        if (tempId != undefined) {
            key = tempId;
        }
        if (key) {
            var arr = this.layersDictionary[key];
            if (!arr) {
                arr = new Array();
                this.layersDictionary[key] = arr;
            }
            arr.push(id);
            
            if (updateCorridor) {
                $("#projectmap").trigger("changeModeOn");
                this.$el.find(".corridorList ul li[data-id='" + key + "']").addClass("modified");

                var template = Handlebars.compile(HTMLSubcorridorLink);
                var html = template(linkData);
                this.$el.find(".corridorList ul li[data-id='" + key + "'] table tbody").append(html);
                this.sortSubcorridor(key);
            }
            else {
                var entityId = linkData;
                $(".corridorList td.link[data-value='" + entityId + "']").closest("tr").attr("data-leaflet", id);
            }
        }

    },
    //remove selected layer from current editable subcorridor
    removeSelectedLayer: function (id, updateCorridor) {
        if (this.currentSubcorridor) {
            var arr = this.layersDictionary[this.currentSubcorridor];
            if (arr) {
                var index = arr.indexOf(id);
                if (index > -1) {
                    arr.splice(index, 1);
                    if (updateCorridor) {
                        $("#projectmap").trigger("changeModeOn");
                        this.$el.find(".corridorList ul li[data-id='" + this.currentSubcorridor + "']").addClass("modified");
                        this.$el.find(".corridorList li.selecting tr[data-leaflet='" + id + "']").remove();
                        this.sortSubcorridor(this.currentSubcorridor);
                    }
                }

            }
        }
    },
    // update layer (link or nodes) on the corridor network
    updateSelectedLayer: function (linkData) {
        this.$el.find(".corridorList tr[data-leaflet='" + linkData.leaflet_id + "'] td.link span").html(linkData.link.name);

        this.$el.find(".corridorList tr[data-leaflet='" + linkData.leaflet_id + "'] td.link div.link").css("background-color", linkData.linkColor);
        

        if (linkData.nodeFrom) {
            this.$el.find(".corridorList td.node[data-value='" + linkData.nodeFrom.entityId + "'] img").attr("title", linkData.nodeFrom.name);
            this.$el.find(".corridorList td.node[data-value='" + linkData.nodeFrom.entityId + "'] img").attr("src", linkData.nodeFrom.img);
        }
        if (linkData.nodeTo) {
            this.$el.find(".corridorList td.node[data-value='" + linkData.nodeTo.entityId + "'] img").attr("title", linkData.nodeTo.name);
            this.$el.find(".corridorList td.node[data-value='" + linkData.nodeTo.entityId + "'] img").attr("src", linkData.nodeTo.img);
        }
        
    },
    sortSubcorridor: function (key) {
        
        //clear previous inverters
        this.$el.find(".corridorList ul li[data-id='" + key + "'] table tbody tr").removeClass("inverted");
        
        var _this = this;
        var $first = this.$el.find(".corridorList ul li[data-id='" + key + "'] table tbody").find("tr").first();
        var linkCount = this.$el.find(".corridorList ul li[data-id='" + key + "'] table tbody tr").length;
        var fullSort = false;
        if ($first) {

            var inverter = function ($tr) {
                $tr.addClass("inverted");
                var $nodeStart = $tr.find("td.node.start").remove();
                $nodeStart.removeClass("start").addClass("end");

                var $nodeEnd = $tr.find("td.node.end").remove();
                $nodeEnd.removeClass("end").addClass("start");

                $tr.find("td.link").before($nodeEnd);
                $tr.find("td.link").after($nodeStart);

                if ($tr.find("td.link span").text().indexOf(" - ") >= 0) {
                    $tr.find("td.link span").html($nodeEnd.find("img").attr("title") + " - " + $nodeStart.find("img").attr("title"));
                }

            }
            var iterator = function (pos, node) {
                if (node) {

                    var $trs = _this.$el.find(".corridorList ul li[data-id='" + key + "'] table tbody tr");
                    // search for start with node 'node'
                    var found = undefined;
                    for (var nn = pos + 1; nn < $trs.length; nn++) {
                        if (node == $trs.eq(nn).find("td.node.start img").attr("title")) {
                            found = $trs.eq(nn);
                            break;
                        }
                    }
                    if (!found) {
                        // search for end with node 'node'
                        for (var nn = pos + 1; nn < $trs.length; nn++) {
                            if (node == $trs.eq(nn).find("td.node.end img").attr("title")) {
                                inverter($trs.eq(nn));
                                found = $trs.eq(nn);
                                break;
                            }
                        }
                    }
                    if (found) {
                        // swith pos
                        found.remove();
                        $trs.eq(pos).after(found);
                        if (linkCount <= pos + 2)
                            fullSort = true;
                        else 
                            iterator(pos + 1, found.find("td.node.end img").attr("title"));
                    }
                    else {

                        if (pos == 0 && !$trs.eq(0).hasClass("inverted")) {
                            //try invert 0 and then sort
                            inverter($trs.eq(0));
                            iterator(0, $trs.eq(0).find("td.node.end img").attr("title"));
                        }
                        /*  no hace falta seguir ordenando si esta mal
                        else {
                            iterator(pos + 1, $trs.eq(pos + 1).find("td.node.end img").attr("title"));
                        }
                        */
                    }
                    $trs = null;
                }
            };
        }

        iterator(0, $first.find("td.node.end img").attr("title"));
        $first.removeClass("inverted");

        if (!fullSort) {

            if (this.currentSortLink) {
                var oldFirst = $first.closest("tbody").find("tr[data-leaflet='" + this.currentSortLink + "']").detach();
                $first.closest("tbody").append(oldFirst);
                $first.before(oldFirst);
                this.currentSortLink = null;
                this.sortSubcorridor(key);
                return false;
            }
        }
        return true;
    },
    removeLayerFromMap: function (id) {
        this.$el.find(".corridorList tr[data-leaflet='" + id + "']").remove();
        var _this = this;
        this.$el.find(".corridorList ul li").each(function (ii, item) {
            var arr = _this.getLayersFromLi($(this));
            if (arr) {
                var index = arr.indexOf(id);
                if (index > -1) {
                    arr.splice(index, 1);
                    $(this).addClass("modified");
                }
            }
        });

    },
    // return corridors and subcorridors data for save
    getCorridorsData: function (workLayer) {

        
        var res = {};
        var corridors = [];
        var _this = this;
        $(".leaflet-infobar .generalinfo .corridor-container .corridorList").each(function (nn, item) {

            if ($(this).hasClass("modified") || $(this).find(".subcorridorItemContainer li").hasClass("modified")) {

                var corr = {
                        entityId: $(this).attr("data-entity-id"),
                        tempId: $(this).attr("data-id"),
                        name: $(this).find("span.corridor-title").text(),
                        childrens:[]
                };

                $(this).find(".subcorridorItemContainer li").each(function (ii, item2) {

                    if ($(this).hasClass("modified")){

                        var extraData = "";
                        var arr = _this.getLayersFromLi($(this));
                        if (arr && arr.length > 0) {
                            // search for entityId
                            $.each(arr, function (ii, leaflet_id) {
                                var layer = workLayer.getLayer(leaflet_id);
                                if (layer && layer.options.entityId) {
                                    if (extraData != "")
                                        extraData += ",";
                                    extraData += layer.options.entityId;
                                }
                            });
                            //end search
                        }

                        var firstEntityid = -1;
                        var firstGeoId = $(this).find("tr").first().attr("data-leaflet");
                        var layer = workLayer.getLayer(firstGeoId);
                        if (layer && layer.options.entityId) {
                            firstEntityid = layer.options.entityId
                        }


                        corr.childrens.push({
                            entityId: $(this).attr("data-entity-id"),
                            tempId: $(this).attr("data-id"),
                            name: $(this).find("a").text(),
                            isFree: false,
                            extraData:extraData,
                            childrens: [],
                            firstEntityid: firstEntityid,
                            firstGeoId: firstGeoId
                        });

                    }

                });
                corridors.push(corr);
            }

            
        });

        res.corridors = corridors;
        res.deletedCorridors = this.deletedCorridors;
        res.deletedSubcorridors = this.deletedSubcorridors;

        return res;
    },
      // set corridors and subcorridors data
    setCorridorData: function (corridors, skipClear) {
        var _this = this;

        if (skipClear) {

        // add and update corridors / subcorridors
        $.each(corridors, function (ii, corridor) {

            if (_this.$el.find(".corridorList[data-entity-id='" + corridor.entityId + "']").length == 0) {
                _this.addCorridor(corridor);
            }
            else {
                //update name
                _this.$el.find(".corridorList[data-entity-id='" + corridor.entityId + "'] span.corridor-title").html(corridor.name);
                _this.$el.find(".corridorList[data-entity-id='" + corridor.entityId + "']").attr("data-id", corridor.tempId);
            }

            
            $.each(corridor.childrens, function (nn, subcorridor) {
                if (_this.$el.find(".corridorList .subcorridorItemContainer li[data-entity-id='" + subcorridor.entityId + "']").length == 0) {
                    _this.addSubcorridor(subcorridor, corridor.tempId);
                }
                else {
                    //update name
                    _this.$el.find(".corridorList .subcorridorItemContainer li[data-entity-id='" + subcorridor.entityId + "'] a.subcorridor").html(subcorridor.name);
                }
            });
        });

        //delete old corridors / subcorridors
        this.$el.find(".corridorList").each(function (ii, item) {
            if ($(item).attr("data-entity-id")) {
                var corr_id = $(item).attr("data-entity-id");
                var found;
                for (var nn = 0; nn < corridors.length; nn++) {
                    if (corridors[nn].entityId == corr_id) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    $(item).remove();
                }
            }
        });
        
        this.$el.find(".corridorList .subcorridorItemContainer li").each(function (ii, item) {
            if ($(item).attr("data-entity-id")) {
                var subcorr_id = $(item).attr("data-entity-id");
                var found;
                for (var nn = 0; nn < corridors.length; nn++) {
                    for (var jj = 0; jj < corridors[nn].childrens.length; jj++) {
                        if (corridors[nn].childrens[jj].entityId == subcorr_id) {
                            found = true;
                            break;
                        }
                    }
                }
                if (!found) {
                    $(item).remove();
                }
            }
        });

        }
        else {
            this.clearContent();

            var template = Handlebars.compile(HTMLCorridorFull);    
            var html = template(corridors);
            this.$el.find(".corridor-container .errorList").before(html);
            this.addSubcorridorSortable();
            
        }

        

        
        // Show assign demand button
        $(".leaflet-infobar .generalinfo button[data-rel='assign_demand_costs']").show();
    },
      // update id's generated in save
    updateCorridorData: function (data) {
        var _this = this;
        $.each(data.corridors, function (ii, corridor) {
            
            _this.$el.find(".corridorList[data-id='" + corridor.tempId + "']").attr("data-entity-id", corridor.entityId);
            $.each(corridor.childrens, function (nn, subcorridor) {
                _this.$el.find(".corridorList .subcorridorItemContainer li[data-id='" + subcorridor.tempId + "']").attr("data-entity-id", subcorridor.entityId);
            });
            
        });

        $.each(data.geometries, function (ii, geo) {
            if (geo.geometryType == 1) { //node
                $(".leaflet-infobar .generalinfo .subcorridorItemContainer li table td.node[data-leaflet='" + geo.geometryId + "']").attr("data-value", geo.entityId);
            }
            else { //link
                $(".leaflet-infobar .generalinfo .subcorridorItemContainer li table td.link[data-leaflet='" + geo.geometryId + "']").attr("data-value", geo.entityId);
            }
        });

        this.deletedCorridors = [];
        this.deletedSubcorridors = [];
        this.$el.find(".corridorList").removeClass("modified");
        this.$el.find(".corridorList ul li").removeClass("modified");
        

    },
    clearContent: function () {
        this.$el.find(".corridorList").remove();
    },
      // return array of leaflet id's of links in subccorridor
    getLinksIdsInSubCorridor: function (id) {
        var $li = this.$el.find(".corridorList ul li[data-entity-id='" + id + "']");
        if ($li){
            return this.getLayersFromLi($li);
        }
    },
    updateHasChanges: function (hasChanges) {
        if (hasChanges) {
            $(".leaflet-infobar .generalinfo button[data-rel='save']").addClass("btn-red");
        }
        else {
            $(".leaflet-infobar .generalinfo button[data-rel='save']").removeClass("btn-red");
        }
    },
    updateMode: function (mode) {
        if (mode != "selectLinks") {
            $(".leaflet-infobar .generalinfo .subcorridorItemContainer li").removeClass("selecting");

        }
    },
    clearContent: function () {
        $(".leaflet-infobar .generalinfo .errorList").hide();
        $(".leaflet-infobar .generalinfo .integrityErrorOn").hide();
        $(".leaflet-infobar .generalinfo .corridorList").remove();
        $(".leaflet-infobar fpcase-title").html("");
    },
    markWithData: function (dataInFPCase) {
        var _this = this;

        $.each(dataInFPCase.links, function (ii, item) {
            _this.$el.find(".corridor-container table td[data-value='" + item + "'] span").removeClass("nodata");
        });
        $.each(dataInFPCase.nodes, function (ii, item) {
            _this.$el.find(".corridor-container table td[data-value='" + item + "'] img").removeClass("nodata");
        });

    },
    highlightLinks: function (arr) {
        this.$el.find(".subcorridorItemContainer table tr").removeClass("selected");
        this.$el.find(".subcorridorItemContainer a.subcorridor").removeClass("selected");

        if (arr) {
            var _this = this;

            $.each(arr, function (nn, leaflet_id) {
                _this.$el.find(".subcorridorItemContainer table tr[data-leaflet='" + leaflet_id + "']").addClass("selected");

                //mark subcorridor
                _this.$el.find(".subcorridorItemContainer li").each(function (ii, item) {
                    var arr = _this.getLayersFromLi($(item));
                    if (arr && arr.indexOf(leaflet_id) >= 0) {
                        $(item).find("a.subcorridor").addClass("selected");
                    }
                });
            });
        }
    },
    getLayersFromLi: function ($li) {
        return this.layersDictionary[$li.attr("data-id")];
    }
  });
  return view;
});


